<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>1</title>
</head>

<body>
    <div id="fade-obj" style="width:300px;height:300px;background:#000"></div>
    <button id="fade-btn">淡出</button>

</body>
<script>
    var btn = document.getElementById("fade-btn");
    var obj = document.getElementById("fade-obj");
    var opacity = document.getElementById("fade-obj").style.opacity;
    var timer;
    btn.addEventListener("click", fade);

    function fade() {
        btn.disabled = true;
        var text = btn.innerHTML;
        clearInterval(timer);
        if (text == "淡出") {
            /*   opacity = 1; */
            document.getElementById("fade-obj").style.opacity = 1;
            console.log(opacity);
            timer = setInterval(fadeOut, 100);
        } else {
            /*      opacity =0; */
            document.getElementById("fade-obj").style.opacity = 0;
            timer = setInterval(fadeIn, 100);
        }
    }
    //淡出
    function fadeOut() {
        var opacity = document.getElementById("fade-obj").style.opacity;
        if (opacity > 0) {
            document.getElementById("fade-obj").style.opacity = opacity - 0.05;

        } else {
            clearInterval(timer);
            btn.disabled = false;
            btn.innerHTML = "淡入";
        }
    }

    //淡入
    function fadeIn() {
        var opacity = parseFloat(
            document.getElementById("fade-obj").style.opacity
        );
        if (opacity < 1) {
            /*       opacity=opacity+0.05;  */
            document.getElementById("fade-obj").style.opacity = opacity + 0.05;
        } else {
            clearInterval(timer);
            btn.disabled = false;
            btn.innerHTML = "淡出"
        }
    }
</script>

</html>